# coding=utf-8
import os
import socket
import sys
import time
import random
import django

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hack_server.settings")
django.setup()

from api.models import DeviceData

BUF_SIZE = 1024
server_addr = ('0.0.0.0', 8001)
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(server_addr)
while True:
    print "waiting for data"
    data, client_addr = server.recvfrom(BUF_SIZE)
    server.sendto("k", client_addr)
    device_id = '123'
    # 解析数据
    data = data.split('"')
    lac = data[-4]
    ci = data[-2]
    beat = random.randint(80, 120)
    device_data = DeviceData(
        device_id=device_id, lac=lac, ci=ci,
        timestamp=int(time.time()), beat=beat
    )
    device_data.save()
server.close()
